package com.demo.config.apache.util;

import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.beans.factory.annotation.Value;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import static org.opencv.imgcodecs.Imgcodecs.imread;
import static org.opencv.imgproc.Imgproc.*;

/**
 * 使用OpenCV将图片去噪
 */
public class OpenCVUtil {

	@Value("${OpenCV.dllFile}")
	private static String dllFile = "D:\\job\\private\\demo\\src\\main\\resources\\lib\\opencv\\opencv_java490.dll";

	public static BufferedImage denoising(String imagePath) throws IOException {
		System.out.println(dllFile);
		System.load(new File(dllFile).getAbsolutePath());
		Mat image = imread(imagePath); // 加载图像
		Mat gray = new Mat();
		cvtColor(image, gray, COLOR_BGR2GRAY);// 灰度化

		Mat bin = new Mat();
		threshold(gray, bin, 170, 200, THRESH_BINARY);// 二值化

		return Mat2BufferedImage(image);

	}

	// Mat 转 BufferedImage
	public static BufferedImage Mat2BufferedImage(Mat matrix) throws IOException {
		MatOfByte mob = new MatOfByte();
		Imgcodecs.imencode(".png", matrix, mob);
		return ImageIO.read(new ByteArrayInputStream(mob.toArray()));
	}

}
